from __future__ import annotations

import os
from dataclasses import dataclass
from typing import Optional

from qiniu import Auth, put_file


# Hardcoded Qiniu credentials per user request
QINIU_ACCESS_KEY = ""
QINIU_SECRET_KEY = ""
QINIU_BUCKET = ""
QINIU_DOMAIN = ""


@dataclass
class QiniuConfig:
	access_key: str
	secret_key: str
	bucket: str
	domain: str  # e.g. https://cdn.example.com (no trailing slash)


class QiniuUploader:
	def __init__(self, config: QiniuConfig) -> None:
		self._config = config
		self._auth = Auth(config.access_key, config.secret_key)

	@classmethod
	def from_env(cls) -> "QiniuUploader":
		# Return uploader using hardcoded config
		return cls(QiniuConfig(
			access_key=QINIU_ACCESS_KEY,
			secret_key=QINIU_SECRET_KEY,
			bucket=QINIU_BUCKET,
			domain=QINIU_DOMAIN.rstrip('/'),
		))

	def upload_file(self, file_path: str, object_key: str, public: bool = False) -> str:
		"""Upload file and return accessible URL.

		If the bucket is public, just combine domain + key.
		If private, return a signed temporary URL.
		"""
		token = self._auth.upload_token(self._config.bucket, object_key, 3600)
		ret, info = put_file(token, object_key, file_path)
		if info.status_code != 200:
			raise RuntimeError(f"Qiniu upload failed: {info}")

		base_url = f"{self._config.domain}/{object_key}"
		if public:
			return base_url
		signed_url = self._auth.private_download_url(base_url, expires=3600)
		return signed_url
